package com.shanghaionstar.discover.geofence;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.text.Editable;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.framework.annotation.ContentView;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.annotation.OnClick;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.mag.poi.FavoriteEntity;
import com.onstar.cn.sqlite.entities.PoiSearchHistory;
import com.onstar.cn.map.common.PoiItemInfo;
import com.onstar.cn.weight.CustomImageView;
import com.onstar.cn.weight.DeleteEditText;
import com.onstar.cn.weight.ProgressLayout;
import com.shanghaionstar.R;
import com.shanghaionstar.discover.adapter.NavPoiSearchHistoryAdapter;
import com.shanghaionstar.discover.adapter.PoiSearchListAdapter;
import com.shanghaionstar.discover.geofence.iview.IGeofenceCenterView;
import com.shanghaionstar.discover.geofence.presenter.GeofenceCenterPresenter;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.swipe.SwipeActivity;
import com.shanghaionstar.utils.BusinessUtil;

import java.util.List;

/**
 * Created by 7828wc on 2016/3/22.
 */
@ContentView(R.layout.discover_setting_home_address)
public class GeofenceCenterActivity extends SwipeActivity implements IGeofenceCenterView {
    @FindViewById
    private DeleteEditText edit_search_addressinfo;
    @FindViewById
    private CustomImageView right_btn;
    @FindViewById
    private CustomImageView left_btn_back;
    @FindViewById
    private Button btn_my_location, btn_map_choos_point, btn_favorites, btn_clean_history_record;
    @FindViewById
    private ListView listview_mylocation, poilist_view;
    @FindViewById
    private TextView no_list_data;
    @FindViewById
    private ProgressLayout progress_layout;

    private GeofenceCenterPresenter presenter;

    private PoiSearchListAdapter poiSearchListAdapter;

    //搜索历史
    private NavPoiSearchHistoryAdapter poiSearchHistroyListAdapter;
//    private ProgressDialog loadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        presenter = new GeofenceCenterPresenter(getScheduler());
        presenter.setView(this);
        presenter.init();
        presenter.showHistoryDatas();
        btn_map_choos_point.setText(R.string.poi_route_vehicle_str);
        right_btn.setBackgroundResource(R.drawable.onstar_nav_right_search);
        left_btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        edit_search_addressinfo.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    presenter.search(edit_search_addressinfo.getText().toString().trim(), edit_search_addressinfo);
                    return true;
                }
                return false;
            }
        });

        edit_search_addressinfo.setOnTextChangeListener(new DeleteEditText.OnTextChangeListener() {
            @Override
            public void textChangeListener(View view, CharSequence text) {
                if (CommonUtil.isNull(text.toString())) {
                    right_btn.setVisibility(View.GONE);
                } else {
                    right_btn.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                String datainfo = edit_search_addressinfo.getText().toString().trim();
                if ("".equals(datainfo)) {
                    edit_search_addressinfo.clearFocus();
                    poilist_view.setVisibility(View.GONE);
                    presenter.showHistoryDatas();
                }
            }
        });

        //搜索历史记录列表
        listview_mylocation.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                edit_search_addressinfo.setText("");
                presenter.onItemClick(position);
            }
        });

        //搜索结果信息列表
        poilist_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                edit_search_addressinfo.setText("");
                presenter.poilistItemClick(position);
            }
        });

        //需初始化当前位置
        presenter.getLocationAndCity();
    }

    @Override
    public BasePresenter getPresenter() {
        return presenter;
    }

    public ProgressDialog showLoading() {
        ProgressDialog mDialog = new ProgressDialog(this);
        mDialog.setTitle(getString(R.string.sendingRequest));
        mDialog.setMessage(getString(R.string.waiting));
        mDialog.setCanceledOnTouchOutside(false);
        return mDialog;
    }

    @Override
    public void showDatas(List<PoiItemInfo> resultList, boolean isLoadingMore) {
        presenter.setNextPage(resultList);
        // ListView 设置滚动监听，滑动到底部自动刷新
        poilist_view.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                presenter.setLastItemIndex(firstVisibleItem, visibleItemCount);
            }

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                presenter.onScrollStateChanged(scrollState, poiSearchListAdapter.getCount());
            }
        });
        presenter.showMore(isLoadingMore, resultList);
    }

    @Override
    public void showNoData() {
        if (poiSearchListAdapter != null) {
            poiSearchListAdapter.notifyDataSetChanged();
        }
        no_list_data.setText(getString(R.string.poi_no_search));
        showNoDatasView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.finish();
        presenter = null;
    }

    @Override
    public void notifyChange() {
        poiSearchListAdapter.notifyDataSetChanged();
    }

    @Override
    public void showPoiList(List<PoiItemInfo> searchPoiList) {
        poiSearchListAdapter = new PoiSearchListAdapter(searchPoiList, this, false, -1);
        poilist_view.setAdapter(poiSearchListAdapter);
        poilist_view.setVisibility(View.VISIBLE);
        listview_mylocation.setVisibility(View.GONE);
        btn_clean_history_record.setVisibility(View.GONE);
        no_list_data.setVisibility(View.GONE);
        setLoading(false);
//        if (loadingDialog != null && loadingDialog.isShowing()) {
//            loadingDialog.dismiss();
//        }
    }

    @Override
    public void showMyLoading() {
//        loadingDialog = showLoading();
//        loadingDialog.setMessage(getString(R.string.poi_searching));
//        loadingDialog.show();
    }

    @Override
    public void onSuccess(List<PoiItemInfo> searchPoiList) {
        if (poiSearchListAdapter != null) {
            poiSearchListAdapter.notifyDataSetChanged();
        } else {
            poiSearchListAdapter = new PoiSearchListAdapter(searchPoiList, GeofenceCenterActivity.this, false, -1);
            poilist_view.setAdapter(poiSearchListAdapter);
        }
        poilist_view.setOnScrollListener(null);
        poilist_view.setVisibility(View.VISIBLE);
        listview_mylocation.setVisibility(View.GONE);
        btn_clean_history_record.setVisibility(View.GONE);
        no_list_data.setVisibility(View.GONE);
        setLoading(false);
//        if (loadingDialog != null && loadingDialog.isShowing()) {
//            loadingDialog.dismiss();
//        }
    }

    private void showNoDatasView() {
        no_list_data.setVisibility(View.VISIBLE);
        poilist_view.setVisibility(View.GONE);
        listview_mylocation.setVisibility(View.GONE);
        btn_clean_history_record.setVisibility(View.GONE);
    }


    @OnClick({R.id.right_btn, R.id.btn_my_location, R.id.btn_map_choos_point, R.id.btn_favorites, R.id.btn_clean_history_record})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.right_btn://搜索
                presenter.search(edit_search_addressinfo.getText().toString().trim(), edit_search_addressinfo);
                break;
            case R.id.btn_my_location://我的位置
                BusinessUtil.sendReportByClickType(GeofenceCenterActivity.this, FunctionNameFindId.Geofencingsetting_currentlocation.getStringValue());
                presenter.myLocationClick();
                break;
            case R.id.btn_map_choos_point://地图选点
                BusinessUtil.sendReportByClickType(GeofenceCenterActivity.this, FunctionNameFindId.Geofencingsetting_vehiclelocation.getStringValue());
                presenter.choosePoint();
                break;
            case R.id.btn_favorites://收藏夹
//                loadingDialog = showLoading();
//                loadingDialog.show();
                BusinessUtil.sendReportByClickType(GeofenceCenterActivity.this, FunctionNameFindId.Geofencingsetting_favorite.getStringValue());
                presenter.start();
//                getFavoriteDestinationList();
                break;
            case R.id.btn_clean_history_record://清空搜索记录
                presenter.clearHistory();
                poiSearchHistroyListAdapter.notifyDataSetChanged();
                break;
            default:
                break;
        }
    }


    @Override
    public void setLoading(boolean isLoading) {
        progress_layout.setVisibility(isLoading ? View.VISIBLE : View.GONE);
//        if(isLoading){
//            loadingDialog = showLoading();
//            loadingDialog.show();
//        }else{
//            if (loadingDialog != null && loadingDialog.isShowing()) {
//                loadingDialog.dismiss();
//            }
//        }
    }

    @Override
    public void onResponseError(OnStarException e) {
//        if (loadingDialog != null && loadingDialog.isShowing()) {
//            loadingDialog.dismiss();
//        }
        setLoading(false);
        no_list_data.setText(getString(R.string.no_favorite_list_data));
        showNoDatasView();
    }

    @Override
    public void onReponseSuccess(List<FavoriteEntity> object) {
//        if (loadingDialog != null && loadingDialog.isShowing()) {
//            loadingDialog.dismiss();
//        }
        setLoading(false);
        presenter.onSuccess(object);
    }

    @Override
    public Activity onActivity() {
        return this;
    }

    @Override
    public void showHistoryDatas(List<PoiSearchHistory> searchHistoryList) {
        if (searchHistoryList != null && searchHistoryList.size() > 0) {
            poiSearchHistroyListAdapter = new NavPoiSearchHistoryAdapter(searchHistoryList, this, "gone");
            listview_mylocation.setAdapter(poiSearchHistroyListAdapter);
            poiSearchHistroyListAdapter.notifyDataSetChanged();
        }

        if (searchHistoryList != null && searchHistoryList.size() > 0) {
            listview_mylocation.setVisibility(View.VISIBLE);
            btn_clean_history_record.setVisibility(View.VISIBLE);
            poilist_view.setVisibility(View.GONE);
            no_list_data.setVisibility(View.GONE);
            if (poiSearchHistroyListAdapter == null) {
                poiSearchHistroyListAdapter = new NavPoiSearchHistoryAdapter(searchHistoryList, this, "gone");
                listview_mylocation.setAdapter(poiSearchListAdapter);
            } else {
                poiSearchHistroyListAdapter.notifyDataSetChanged();
            }
        } else {
            listview_mylocation.setVisibility(View.VISIBLE);
            btn_clean_history_record.setVisibility(View.GONE);
            poilist_view.setVisibility(View.GONE);
            no_list_data.setVisibility(View.GONE);
        }
    }
}
